package com.rk.applist;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.rk.adapter.AppAdapter;
import com.rk.adapter.AppPagerAdapter;
import com.rk.entity.AppInfo;
import com.rk.listener.AppOnPageChangeListener;
import com.rk.listener.IPageChangeCallback;
import com.rk.util.DisplayUtils;
import com.rk.util.LayoutUtils;
import com.carboy.launch.R;
import com.carboy.launch.activity.column.BaseActivity;

@SuppressLint("NewApi") 
public class AppListActivity extends BaseActivity implements IPageChangeCallback {

    private static final String TAG = "AppListActivity";
    private static final int NUMROWS = 3;
    private ViewPager mViewPager;
    private LinearLayout mLinearLayout;
    private List<View> mGridViews;
    private List<AppInfo> mAppInfos;
    private List<AppInfo> mTmpAppInfos;
    private List<AppAdapter> mAppAdapters;
    private List<ImageView> mImageViews;
    private AppPagerAdapter mAppPagerAdapter;
    private int mNumColumns;
    private int mItemWidth;
    private int mItemHeight;
    private int mBottomHeight;
    private int mPageCount;
    boolean hasMeasured = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_applist);
        
        initViews();
        initStatusBar();
        initDatas();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    private void initDatas() {
        getParameter();
        mAppInfos = queryAppInfo();
        mGridViews = new ArrayList<View>();
        mAppAdapters = new ArrayList<AppAdapter>();
        int pageApps = mNumColumns * NUMROWS;
        mPageCount = mAppInfos.size() % pageApps == 0 ? mAppInfos.size() / pageApps : mAppInfos.size() / pageApps + 1;
        Log.e(TAG, "mPageCount:" + mPageCount);
        for(int i=0; i < mPageCount; i++) {
            mTmpAppInfos = new ArrayList<AppInfo>();
            for(int j = i * pageApps; j < (i+1)*pageApps; j++) {
                if(j < mAppInfos.size()) {
                    mTmpAppInfos.add(mAppInfos.get(j));
                } else {
                    break;
                }
            }
            GridView gridView = (GridView) LayoutInflater.from(this).inflate(R.layout.item_page, null);
            gridView.setNumColumns(mNumColumns);
            gridView.setSelector(new ColorDrawable(Color.TRANSPARENT));
            AppAdapter mAppAdapter = new AppAdapter(this, mTmpAppInfos, mItemWidth, mItemHeight);
            mAppAdapters.add(mAppAdapter);
            gridView.setAdapter(mAppAdapter);
            mGridViews.add(gridView);
        }
        mImageViews = new ArrayList<ImageView>();
        for(int i=0; i<mPageCount; i++) {
            ImageView imv = (ImageView) LayoutInflater.from(this).inflate(R.layout.item_bottom, null);
            imv.setPadding(10, 0, 10, 0);
            imv.setImageResource(R.drawable.point_white_n);
            mImageViews.add(imv);
            mLinearLayout.addView(imv);
        }
        mAppPagerAdapter = new AppPagerAdapter(this, mGridViews);
        mViewPager.setAdapter(mAppPagerAdapter);
        mViewPager.setCurrentItem(0);
        mImageViews.get(0).setImageResource(R.drawable.point_white_p);
        mViewPager.setOnPageChangeListener(new AppOnPageChangeListener(this));
    }

    private void initViews() {
        mViewPager = (ViewPager) findViewById(R.id.activity_applist_vp);
        mLinearLayout = (LinearLayout) findViewById(R.id.activity_applist_position);
        ViewTreeObserver vto = mLinearLayout.getViewTreeObserver();
        vto.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
            @Override
            public boolean onPreDraw() {
                if (hasMeasured == false) {
                    mBottomHeight = mLinearLayout.getMeasuredHeight();
                    mBottomHeight = mLinearLayout.getHeight();
                    hasMeasured = true;
                }
                return true;
            } 
        });
    }

    public List<AppInfo> queryAppInfo() {
        PackageManager pm = this.getPackageManager();
        Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
        mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        // get all ResolveInfo.  
        List<ResolveInfo> resolveInfos = pm
                .queryIntentActivities(mainIntent, 0);
        List<AppInfo> appInfos = new ArrayList<AppInfo>();
        Collections.sort(resolveInfos,new ResolveInfo.DisplayNameComparator(pm));
        if (appInfos != null) {
            appInfos.clear();
            for (ResolveInfo reInfo : resolveInfos) {
                String activityName = reInfo.activityInfo.name; 
                String pkgName = reInfo.activityInfo.packageName;
                String appLabel = (String) reInfo.loadLabel(pm);
                Drawable icon = reInfo.loadIcon(pm);

                Intent launchIntent = new Intent();
                launchIntent.setComponent(new ComponentName(pkgName,
                        activityName));

                if(pkgName.equals("com.android.soundrecorder")) {
                    continue;
                }

                AppInfo appInfo = new AppInfo();
                appInfo.setAppName(appLabel);
                appInfo.setPackageName(pkgName);
                appInfo.setActivityName(activityName);
                appInfo.setIcon(icon);
                appInfos.add(appInfo);
                System.out.println(appLabel + " activityName---" + activityName
                        + " pkgName---" + pkgName);
            }  
        }
        Log.e(TAG, "size:" + appInfos.size());
        return appInfos;
    }

    private void getParameter() {
        int padding = DisplayUtils.dip2px(this, getResources().getDimension(R.dimen.layout_size_30dip));
        int availableWidth = LayoutUtils.getInstance(this).getScreenInfo().get(0) - padding;
        int availableHeight = LayoutUtils.getInstance(this).getScreenInfo().get(1)
//                + LayoutUtils.getInstance(this).getNavigationBarHeight()
                - DisplayUtils.dip2px(this, getResources().getDimension(R.dimen.layout_size_25dip))
                - 33;
        Log.e(TAG, "mBottomHeight:" + mBottomHeight);
        Log.e(TAG, availableHeight + "");
        mItemHeight = availableHeight / NUMROWS;
        mNumColumns = availableWidth / (mItemHeight + padding);
        mItemWidth = availableWidth / mNumColumns;
    }

    @Override
    public void getCurrentPosition(int position) {
        for(int i=0; i<mPageCount; i++) {
            if(i == position) {
                mImageViews.get(i).setImageResource(R.drawable.point_white_p);
            } else {
                mImageViews.get(i).setImageResource(R.drawable.point_white_n);
            }
        }
    }
}
